package wre.server;

import java.io.IOException;

import wre.client.RetortService;
import wre.logic.RetortManager;
import wre.shared.FieldVerifier;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;


/**
 * The server side implementation of the RPC service.
 * 
 * @author Adam Smith
 */
@SuppressWarnings("serial")
public class RetortServiceImpl extends RemoteServiceServlet implements
		RetortService {
	
	/** The retort manager. */
	private RetortManager retortManager;

	/**
	 * Instantiates a new retort service impl.
	 */
	public RetortServiceImpl() {
		retortManager = new RetortManager();
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html
	 *            the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}

	/* (non-Javadoc)
	 * @see wre.client.RetortService#retortServer(java.lang.String)
	 */
	@Override
	public String retortServer(String input) throws IllegalArgumentException,
			IOException {
		// Verify that the input is valid.
		if (!FieldVerifier.isValidName(input)) {
			// If the input is not valid, throw an IllegalArgumentException back
			// to
			// the client.
			throw new IllegalArgumentException(
					"Phrase must be at least 4 characters long");
		}

		// Escape data from the client to avoid cross-site script
		// vulnerabilities.
		input = escapeHtml(input);

		return retortManager.doRetort(input);

	}
}
